<?php

namespace app\admin\service;

use app\admin\dao\ProfessionalQaReplyDao;
use app\admin\model\UM as UM;
use app\common\model\ProfessionalQaReply;
use ShidianUtil\Exception\DataNotExistException;
use think\exception\ValidateException;

/**
 * Class ReplyCheckService
 * @package app\professionalqa\service
 */
class ReplyCheckService
{

    private ProfessionalQaReplyDao $professionalQaReplyDao;

    public function __construct(ProfessionalQaReplyDao $professionalQaReplyDao)
    {
        $this->professionalQaReplyDao = $professionalQaReplyDao;
    }

    /**
     * 更新
     * @param \app\admin\model\UM $user
     * @param int $id
     * @param array $params
     * @return \app\common\model\ProfessionalQaReply
     */
    public function modify(UM $user, int $id, array $params): ProfessionalQaReply
    {
        $params['checkStatus'] ??= '1';

        $record = ProfessionalQaReply::field(true)
            ->where('id', $id)
            ->with(['professionalQa', 'member' => ['memberInfo']])
            ->find();

        if (is_null($record)) {
            throw new DataNotExistException('该回答不存在或已被删除');
        }

        if ($record->checkStatus != 0) {
            throw new ValidateException('该回复已经审核，请勿重复操作');
        }

        if ($params['checkStatus'] == '1' && !is_null($record->professionalQa) && $record->professionalQa->isEnd == '1') {
            throw new ValidateException('该问题已经有答案了，请选择不通过');
        }

        $record->checkStatus = $params['checkStatus'];
        $record->save();

        // 如果当前答案通过
        if ($params['checkStatus'] == '1') {

            // 其他答案修改为 不通过
            $this->professionalQaReplyDao->updateActiveByClosure(fn($query) => $query->where('qaId', $record->qaId)->where('id', '<>', $record->id),
                [
                    'checkStatus' => '2',
                ]);

            // 修改问题状态
            if (!is_null($record->professionalQa)) {
                $record->professionalQa->isEnd = '1';
                $record->professionalQa->answer = $record->replyContent;
                $record->professionalQa->answer_time = time();
                $record->professionalQa->answer_memberId = $record->memberId;
                $record->professionalQa->save();
            }

            // 修改律师信息
            if (!is_null($record->member) && !is_null($record->member->memberInfo)) {
                $record->member->memberInfo->answerNumber = $record->member->memberInfo->answerNumber + 1;
                $record->member->memberInfo->save();
            }
        }

        // TODO 记录日志

        return $record;
    }
}
